package com.ys.utils.yinsheng.yztdock.util;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * @Description: 读取公私钥配置文件工具类
 *
 * @Author: JI XIANG YUN<br>
 * @create: 2020-06-17 20:52
 **/
public class PropertiesUtil {
    private static final String DEFAULT_RESOURCE_PATTERN = "/yzt.properties";
    private static final Map<Object, Object> all = new HashMap<>();
    private static Logger log = Logger.getAnonymousLogger();
    private static Properties properties = null;
    private static Map<String,String> paramsMap;

    static {
        init();
        paramsMap = new HashMap<>();
        paramsMap.put("active",getObject("active"));
        paramsMap.put("mer.cert.id",getObject("mer.cert.id"));
        paramsMap.put("mer.pfx.path",getObject("mer.pfx.path"));
        paramsMap.put("ys.crt.path",getObject("ys.crt.path"));
        paramsMap.put("mer.pfx.pwd",getObject("mer.pfx.pwd"));
        paramsMap.put("ys.cert.path",getObject("ys.cert.path"));
    }

    public static String getObject(String prepKey) {
        if (properties == null) {
            init();
        }
        return properties.getProperty(prepKey);
    }


    public static Map<String,String> getParamsMap() {
        return paramsMap;
    }


    private static void init() {
        InputStream in = null;
        try {
            log.info("PropertiesUtil|init|waring|开始加载公私钥的信息");
            properties = new Properties();
            String userDir = System.getProperty("user.dir");
            log.info("PropertiesUtil|init|获取根路径"+userDir);
            String filePath = userDir +File.separator + DEFAULT_RESOURCE_PATTERN;
            log.info("PropertiesUtil|init|文件路径" + filePath);
            in = PropertiesUtil.class.getResourceAsStream(DEFAULT_RESOURCE_PATTERN);
            properties.load(new InputStreamReader(in,"UTF-8"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.severe("PropertiesUtil|init|catch error|未发现文件[yzt.properties]请在resources下创建该文件并按规定配置相关参数");
        } catch (IOException e) {
            e.printStackTrace();
            log.severe("PropertiesUtil|init|catch error|读取文件异常" + e.toString() + e.getMessage());
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.severe("PropertiesUtil|init|catch|文件流关闭失败"+e.toString()+e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        Map<String, String> paramsMap = getParamsMap();

        System.out.println(JSONObject.toJSONString(paramsMap));
    }
}
